//
//  UserAccount.swift
//  SwiftWeibo
//
//  Created by Lucky on 16/5/11.
//  Copyright © 2016年 Lucky. All rights reserved.
//

import UIKit
import SVProgressHUD

class UserAccount: NSObject, NSCoding{

    //用于调用access_token，接口获取授权后的access_token
    var access_token: String?
    
    //access_token的生命周期，单位是秒
    var expires_in: NSNumber? {
        didSet {
            expires_Date = NSDate(timeIntervalSinceNow:expires_in!.doubleValue)
            print(expires_Date)
        }
    }
    
    //保存用户过期时间
    var expires_Date:NSDate?
    
    //当前授权用户的UID
    var uid: String?
    
    //保存用户的头像地址（大图）
    var avatar_large: String?
    
    //用户昵称
    var screen_name: String?
    
    init(dict: [String: AnyObject]!) {
        
        super.init()

        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description: String {
        
        let properties = ["access_token", "expires_in", "uid", "expires_Date", "avatar_large", "screen_name"]
        
        let dict = self.dictionaryWithValuesForKeys(properties)
        
        return "\(dict)"
    }
    
    func loadUserInfo(success: (account: UserAccount)->(), failure: (error: NSError?)->()) {
        assert(access_token != nil, "没有授权")
        
        let path = "2/users/show.json"
        let params = ["access_token":access_token!, "uid":uid!]
        
        NetworkTools.shareNetworkTools().GET(path, parameters: params, success: { (_, JSON) in
            print(JSON)
            
            if let dict = JSON as? [String: AnyObject] {
                self.screen_name = dict["screen_name"] as? String
                self.avatar_large = dict["avatar_large"] as? String
                
                success(account: self)
                
                return
            }
            
            failure(error: nil)
        
            }) { (_, error) in
                print(error)
                failure(error: error)
        }
    }
    
    /**
     返回用户是否登陆
     */
    class func userLogin() -> Bool {
        return UserAccount.loadAccount() != nil
    }
    
    // MARK: - 保存和读取
    func saveAccount() -> () {
        print("account.plist".cacheDir())
        
        NSKeyedArchiver.archiveRootObject(self, toFile: "account.plist".cacheDir())
    }
    
    static var account: UserAccount?
    
    class func loadAccount() -> UserAccount? {
        print("path***:" + "account.plist".cacheDir())
        
        if account != nil {
            return account
        }
        
        //判断授权信息是否过期
        if account?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            return nil
        }
        
        account = NSKeyedUnarchiver.unarchiveObjectWithFile("account.plist".cacheDir()) as? UserAccount
        return account
    }
    
    // MARK: - NSCoding
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }

}
